package com.guslegend.interceptor;

import com.guslegend.enums.BizCodeEnum;
import com.guslegend.model.LoginUser;
import com.guslegend.util.CommonUtil;
import com.guslegend.util.JWTUtil;
import com.guslegend.util.JsonData;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: guslegend
 * @description: 登录拦截器
 * @create: 2025-05-28 19:33
 **/
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<LoginUser>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拿到token
        String accessToken = request.getHeader("token");
        if (accessToken == null) {
            accessToken = request.getParameter("token");
        }
        log.info("Access token: " + accessToken);
        //token不为空
        if (StringUtils.isNotBlank(accessToken)) {
            Claims claims = JWTUtil.checkJWT(accessToken);
            log.info("claims: " + claims);
            //            token无效
            if (claims == null) {
                CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_ILLEGAL_LOGIN));
                return false;
            }
            Long id = Long.valueOf(claims.get("id").toString());
            String headImg = claims.get("head_img").toString();
            String name = claims.get("name").toString();
            String mail = claims.get("mail").toString();
            LoginUser loginUser = LoginUser.builder().id(id).name(name).mail(mail).headImg(headImg).build();
            //传递登录用户信息
//            request.setAttribute("loginUser", loginUser);

            //通过threadLocal传递用户登录对象
            threadLocal.set(loginUser);
            return true;
        }
        CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
